package com.demo.order.config;

import com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.BlockExceptionHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.authority.AuthorityException;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeException;
import com.alibaba.csp.sentinel.slots.block.flow.FlowException;
import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowException;
import com.alibaba.csp.sentinel.slots.system.SystemBlockException;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;

/**
 * @author wuyijie
 * @className: CustomBolckExceptionHandler
 * @description: TODO sentinel 异常处理器。sentinel默认抛出blockexception的5个子类
 * @date 2021/3/30 16:45
 */
@Component
@Slf4j
public class CustomBlockExceptionHandler implements BlockExceptionHandler {
    @Override
    public void handle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, BlockException e) throws Exception {
        HashMap<String, Object> result = new HashMap<>(2);
        String requestURI = httpServletRequest.getRequestURI();
        log.error("Sentinel BlockException ,requestURI : {}",requestURI);
        if (e instanceof FlowException){
            result.put("code",-1);
            result.put("msg","FlowException");

        }else if (e instanceof DegradeException){
            result.put("code",-2);
            result.put("msg","DegradeException");

        }else if (e instanceof ParamFlowException){
            result.put("code",-3);
            result.put("msg","ParamFlowException");

        }else if (e instanceof SystemBlockException){
            result.put("code",-4);
            result.put("msg","SystemBlockException");

        }else if (e instanceof AuthorityException){
            result.put("code",-5);
            result.put("msg","AuthorityException");

        }
        httpServletResponse.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        httpServletResponse.setContentType("application/json;charset=utf-8");

        ObjectMapper objectMapper = new ObjectMapper();
//        某个字段为null时，不进行序列化输出
        objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        objectMapper.writeValue(httpServletResponse.getWriter(),result);
    }
}
